package org.gd.httprequests.lib;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.*;

/**
 *
 * @author Gorhover Dmitriy
 */
public class Util {

    private static Util util = null;

    public static Util getInstance() {
        if(util == null) {
            util = new Util();
        }
        return util;
    }

    /**
     * Logger
     */
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * Урл, по которому будет отправлен XML запрос.
     * 
     * @return 
     */
    /**
	 * отправляет XML запроc.
	 * 
	 * @param url
	 * @param xml
	 * @return 
	 */
	public String sendXmlRequest(String url, String xml) {
		String response = null;
		try {
			response = Http.Request(url, "POST", xml, "UTF-8");
		} catch (NullPointerException e) {
			logger.error("[sendXmlRequest]: NullPointerException at line {}",
                    e.getStackTrace()[0].getLineNumber(), e);
		} catch (Exception e) {
			logger.error("[sendXmlRequest]: Exception: {}: {}",
                    e.getClass().getName(), e.getMessage());
		}
		return response;
	}

    public String sendXmlRequest(String url, String xml, int connTimeout, int readTimeout) {
        String response = null;
        try {
            response = Http.RequestTimeout(url, "POST", xml, "UTF-8", connTimeout, readTimeout);
        } catch (NullPointerException e) {
            logger.error("[sendXmlRequest]: NullPointerException at line {}",
                    e.getStackTrace()[0].getLineNumber(), e);
        } catch (Exception e) {
            logger.error("[sendXmlRequest]: Exception: {}: {}",
                    e.getClass().getName(), e.getMessage());
        }
        return response;
    }

    /**
     * Сортировка списка. 
     * 
     * @param list 
     */
    public static void sortList(List<? extends String> list) {
        Collections.sort(list, new Comparator() {
            @Override
            public int compare(Object obj0, Object obj1) {
                String c0 = (String) obj0;
                String c1 = (String) obj1;
                if (c0.compareTo(c1) < 0) {
                    return -1;
                } else {
                    if (c0.compareTo(c1) > 0) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
            }
        });
    }
    /**
     * Map to XML
     * 
     * @param map
     * @return 
     */
    public static String MapToXML(Map<? extends String, ? extends String> map) {
        StringBuilder xml = new StringBuilder();
        if(!map.isEmpty()) {
            Iterator<? extends String> iterator = map.keySet().iterator();
            while(iterator.hasNext()) {
                String param = iterator.next();
                String value = map.get(param);
                xml.append("<").append(param).append(" value=\"").append(value).append("\" />");
            }            
        }
        return xml.toString();
    }

    /**
     *
     * @param str
     * @return
     */
    public static InputStream StringToInputStream(String str) /*throws IOException*/ {
        InputStream is = new ByteArrayInputStream(str.getBytes());
        return is;
    }

    /**
     *
     * @param outputStream
     * @return
     * @throws java.io.IOException
     */
    public static String OutputStreamToString(OutputStream outputStream) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos.writeTo(outputStream);
        return new String(baos.toByteArray());

    }
}
